import 'package:faker/models/article.dart';
import 'package:sqflite/sqlite_api.dart';

import 'base_provider.dart';

class ReadLaterRssProvider extends BaseDbProvider {
  final String tbName = "readlt_rss";

  final String columnId = "id";
  final String columnTitle = "title";
  final String columnDescription = "description";
  final String columnLink = "link";
  final String columnGuid = "guid";
  final String columnPubDate = "pubDate";
  final String columnAuthor = "author";

  ReadLaterRssProvider();

  @override
  tableName() {
    return tbName;
  }

  @override
  createTableString() {
    return '''
        CREATE TABLE $tbName($columnId INTEGER PRIMARY KEY AUTOINCREMENT, $columnTitle TEXT,
        $columnDescription TEXT, $columnLink TEXT, $columnGuid TEXT, $columnPubDate TEXT, $columnAuthor TEXT)
      ''';
  }

  ///查询所有数据库
  Future<List> getAllRdlRssProvider() async {
    Database db = await getDataBase();
    var result = await db.rawQuery("select * from $tbName");
    return result.toList();
  }

  ///查询数据库
  Future<Article> getRdlRssByGuid(String guid) async {
    Database db = await getDataBase();
    var result =
        await db.rawQuery("select * from $tbName WHERE $columnGuid = '$guid'");
    if (result.length == 0) return null;
    return Article.fromMap(result.first);
  }

  ///查询数据库
  Future<bool> checkRdl(String guid) async {
    Database db = await getDataBase();
    var result =
        await db.rawQuery("select * from $tbName WHERE $columnGuid = '$guid'");
    return result != null ? true : false;
  }

  ///插入到数据库
  Future<int> insert(Article item) async {
    Database db = await getDataBase();
    var userProvider = await getRdlRssByGuid(item.guid);
    if (userProvider != null) {
      ///删除数据
      await db.delete(tbName, where: "$columnGuid = ?", whereArgs: [item.guid]);
    }
    var res = await db.insert("$tbName", item.toMap());
    return res;
  }

  Future<void> delete(guid) async {
    Database db = await getDataBase();
    await db.delete(tbName, where: "$columnGuid = ?", whereArgs: [guid]);
  }

  ///更新数据库
  Future<int> update(Article item) async {
    Database db = await getDataBase();
    return await db.update("$tbName", item.toMap());
  }

  /// 关闭数据库
  Future<void> close() async {
    Database db = await getDataBase();
    await db.close();
  }
}
